import React, { useEffect, useState } from "react";
import './home.css';
import '../../App.css'
import '../Proof/proof.css';
import { useHistory, useLocation } from "react-router-dom/cjs/react-router-dom";
import { useDispatch } from "react-redux";
import { isProofContact, isProofFace, isProofFrequentlyUsedApps, isProofMobile } from "@/store/actions/userState";
import NavigateBar from "@/components/NavigateBar";
import icon_home_step1 from '@/assets/icon_home_step1.png'
import icon_home_step2 from '@/assets/icon_home_step2.png'
import icon_home_step3 from '@/assets/icon_home_step3.png'
import icon_home_increase1 from '@/assets/icon_home_increase1.png'
import icon_home_increase2 from '@/assets/icon_home_increase2.png'
import { DotLoading, Mask } from "antd-mobile";
import { PageTag } from "@/utils/pageTag";
import TextCarouselHorizontal from "@/components/TextCarouselHorizontal";
import icon_proof_face_notify from '@/assets/icon_proof_face_notify.png'
import icon_proof_face_more from '@/assets/icon_proof_face_more.png'
import AddHomeEvent from "@/utils/addHomeEvent";
import FacebookData from "@/utils/facebookData";
import { reqHomeCredit, reqSaveEvent, reqSaveLocation, reqUserState } from "@/store/actions/apiServices";


export default function Home() {

    //loading状态
    const [maskVisible, setMaskVisible] = useState(false)
    const [addHomeMaskIsHomeMode, setAddHomeMaskIsHomeMode] = useState(false);

    //显示add home弹框
    const [addHomeMaskVisible, setAddHomeMaskVisible] = useState(false);

    //显示add home弹框
    // const [linkUrl, setLinkUrl] = useState(null);

    // 获取路由历史 history 对象
    const history = useHistory()

    // 获取路由信息 location 对象
    const location = useLocation()

    //获取 Redux 分发器
    const dispatch = useDispatch()

    //获取Redux Store中的额度信息
    const [homeCreditInfo, setHomeCreditInfo] = useState({});

    const onReqUserStateCallback = (success, resObj) => {
        setMaskVisible(false);

        if (success && resObj) {
            if (resObj.isProofFinish === true) {
                history.push("/apply")

            } else if (resObj.isProofFinish === false) {
                if (isProofMobile(resObj.stepTitle)) {
                    history.push('/proofmobile')

                } else if (isProofFrequentlyUsedApps(resObj.stepTitle)) {
                    history.push('/prooffrequentlyapps')

                } else if (isProofFace(resObj.stepTitle)) {
                    history.push('/proofface')

                } else if (isProofContact(resObj.stepTitle)) {
                    if (window.isSupportContactPicker === true) {
                        history.push('/proofcontact')
                    } else {
                        history.push('/proofcontactinput')
                    }
                } else {
                    history.push("/proof")
                }
            }
        }
    };


    //启动时请求首页额度
    useEffect(() => {
        //获取首页额度
        try {
            //添加 fb 像素
            // eslint-disable-next-line no-undef
            // fbq('track', 'Page_Home');
            // eslint-disable-next-line no-undef
            // gtag('track', 'Page_Home');

            reqSaveEvent("HOME_START")

            setMaskVisible(true)
            reqHomeCredit((success, resObj) => {
                setMaskVisible(false);
                if (success && resObj) {
                    setHomeCreditInfo(resObj);
                }
                checkUserLocation();
            });

            return () => {
                reqSaveEvent("HOME_END")
            }

        } catch (e) {
            console.log(e)
        }
    }, [])

    const checkUserLocation = async () => {
        if ("geolocation" in navigator) {
            navigator.geolocation.getCurrentPosition(
                (position) => {
                    console.log("=============查询定位成功返回：")
                    console.log(position)
                    const latitude = position.coords.latitude + ""
                    const longitude = position.coords.longitude + ""
                    reqSaveLocation(longitude, latitude)
                },
                (error) => {
                    console.log("====== 查询定位错误返回：" + error.message)
                    if (error.code === 1) {
                        // 用户拒绝了位置权限
                        console.error("====== 查询定位错误返回: User denied location permission.");
                        reqSaveEvent("LOCATION_PERMISSION_DENIED")
                    } else if (error.code === 2) {
                        // 浏览器无法获取位置信息
                        console.error("====== 查询定位错误返回: Browser cannot determine the location.");
                        reqSaveEvent("LOCATION_CANT_DETERMINE")
                    } else {
                        // 其他错误
                        console.error(`====== 查询定位错误返回: ${error.message}`);
                        reqSaveEvent("LOCATION_ERROR", error.message)
                    }
                }
            );
        } else {
            console.log("=======Geolocation is not available in your browser.")
            reqSaveEvent("LOCATION_NOT_AVAILABLE")
        }
    }

    //点击申请
    const onApplyClick = () => {
        reqSaveEvent("HOME_COMMIT_CLICK")
        setMaskVisible(true);
        reqUserState(PageTag.HOME, onReqUserStateCallback);
    }

    //去朋友首页
    const onHandleToFriendsLink = () => {
        if (FacebookData.facebookUserInfo) {
            const link = FacebookData.facebookUserInfo.link
            console.log("==== open user link: " + link)
            if (link) {
                window.location.href = link
            } else {
                window.location.href = "https://www.facebook.com/id100066806351639/"
            }
        }
    }

    // 点击add home监听
    const onHandleAddToHome = (type) => {
        console.log(`点击add home监听: ${type}`)
        if (type === 'home') {
            AddHomeEvent.onHandleAddHomeEventClick()
        } else {
            AddHomeEvent.onHandleAddFavoriteEventClick()
        }
    }

    // 关闭add home
    const onHandleAddToHomeClose = () => {
        console.log(`点击close add home监听`)
        setAddHomeMaskVisible(false)
    }

    return (
        <div className="homeRoot">
            <div className="homeTopBackground"></div>
            <NavigateBar theme="transparent" onAddFavorite={() => { setAddHomeMaskIsHomeMode(false); setAddHomeMaskVisible(true) }} onAddHome={() => { setAddHomeMaskIsHomeMode(true); setAddHomeMaskVisible(true) }}>Onua Credit</NavigateBar>

            <div className="rowAlignStartFullWidth proofHorPadding16Px" onClick={onHandleToFriendsLink}>
                <div className="proofFaceNotifyContent">
                    <img className="proofFaceImageNotify proofRightMargin6Px" src={icon_proof_face_notify} alt="" />
                    <span className="proofFaceUseFriendsTitle proofRightMargin6Px">Using friends:</span>
                    <div className="proofFaceUseFriendsScrollNotify">
                        <TextCarouselHorizontal className="rowAlignStartFullWidth" />
                    </div>
                    <img className="proofFaceImageNotify" src={icon_proof_face_more} alt="" />
                </div>
            </div>

            <div className="homeAmountContent">
                <div className="homeAmountTitle">Loan Amount</div>

                <div className="contentRowCenter homeAmountAmountBottomAlign">
                    <div className="homeAmountCurrency">{homeCreditInfo.currency}</div>
                    <div className="homeAmountValue">{homeCreditInfo.amount}</div>
                </div>

                <div className="homeApplyBtn" onClick={onApplyClick}>
                    <div className="mainButtonGradient">Apply Now</div>
                </div>
            </div>

            <div className="contentRowCenter contentHorizontalPadding homeRowTopEdge contentVerticalPadding">
                <div className="contentColumnCenter contentWidthAvag ">
                    <img className="homeStepImage" src={icon_home_step1} alt="" />
                    <span className="homeStepTitle">Submit</span>
                    <span className="homeStepDetail">information</span>
                </div>
                <div className="contentColumnCenter contentWidthAvag ">
                    <img className="homeStepImage" src={icon_home_step2} alt="" />
                    <span className="homeStepTitle">Confirm</span>
                    <span className="homeStepDetail">your loan need</span>
                </div>
                <div className="contentColumnCenter contentWidthAvag ">
                    <img className="homeStepImage" src={icon_home_step3} alt="" />
                    <span className="homeStepTitle">Get</span>
                    <span className="homeStepDetail">money</span>
                </div>
            </div>

            <div className="contentColumnCenter homeRowTopEdge contentHorizontalPadding contentVerticalPadding">
                <span className="homeHeaderTitle">Maintain good loan record will continue to increase loan amount.</span>

                <div className="contentRowStart homeInsideTopEdge homeIncreaseContent contentHorizontalPadding">
                    <img className="homeStepImage" src={icon_home_increase1} alt="" />
                    <span className="homeIncreaseTitle">Loan{'\n'}Amount</span>
                    <div className="flexRowStart">
                        <div className="homeIncreaseCurrency">{homeCreditInfo.currency}</div>
                        <div className="homeIncreaseAmount mainTextColor">{homeCreditInfo.increasedAmount1}</div>
                    </div>
                </div>

                <div className="contentRowStart homeInsideTopEdge homeInsideTopEdge homeIncreaseContent contentHorizontalPadding">
                    <img className="homeStepImage" src={icon_home_increase2} alt="" />
                    <span className="homeIncreaseTitle">Loan{'\n'}Amount</span>
                    <div className="flexRowStart">
                        <div className="homeIncreaseCurrency">{homeCreditInfo.currency}</div>
                        <div className="homeIncreaseAmount redTextColor">{homeCreditInfo.increasedAmount2}</div>
                    </div>
                </div>
            </div>

            {/* add home gif dialog */}
            {/* <AddToHomeGifDialog visible={addHomeMaskVisible} onConfirm={onHandleAddToHome} onClose={onHandleAddToHomeClose} isHomeMode={addHomeMaskIsHomeMode} /> */}

            <Mask visible={maskVisible} opacity={0.1}
                onMaskClick={() => { }}>
                <div className="overlayContent">
                    <span style={{ fontSize: 24, color: '#ff3141' }} >
                        <DotLoading color="currentColor" />
                    </span>
                </div>
            </Mask>
        </div>
    )
}